﻿<template>
  <div class="roles">
    <!-- 导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <div>
            <el-button type="primary"
            @click="addRolesDialogVisible = true"
            >添加角色</el-button>
          </div>
        </el-col>
      </el-row>
      <el-table
      :data="roleslist"
      style="width: 100%"
      border
      stripe>
      <!-- 展开列 -->
      <el-table-column
        type="expand"
        width="180">
        <template slot-scope="scope">
          <el-row
          :class="['dbbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
          v-for="(item1, i1) in scope.row.children"
          :key="item1.id">
            <!-- 渲染一级权限 -->
            <el-col :span="5">
              <el-tag  closable
              @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二级和三级权限 -->
            <el-col :span="19">
              <!-- :class="['dbbottom', i2 === 0 ? '' : '']" -->
              <!-- 渲染二级权限 -->
              <el-row
              v-for="(item2, i2) in item1.children"
              :key="item2.id"
              :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
              >
                <el-col :span="6">
                  <el-tag type="success" closable
                 @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-tag
                  v-for="(item3) in item2.children"
                  :key="item3.id"
                  type="warning" closable
                  @close="removeRightById(scope.row, item3.id)">
                  {{item3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <!-- <pre> 标签的一个常见应用就是用来表示计算机的源代码。 -->
          <!-- <pre>{{scope.row}}</pre> -->
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column
        type="index"
        label="#"
        width="180">
      </el-table-column>
      <el-table-column
        prop="roleName"
        label="角色名称"
        width="180">
      </el-table-column>
      <el-table-column
        prop="roleDesc"
        label="角色描述">
      </el-table-column>
      <el-table-column
        label="操作"
        width="300"
        >
        <template slot-scope="scope" >
          <!-- slot-scope="scope" -->
          <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          @click="showEditRole(scope.row.id)"
          >
          编辑</el-button>
          <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="removeRoleById(scope.row.id)"
          >
          删除</el-button>
          <el-button
          type="warning"
          icon="el-icon-setting"
          size="mini"
          @click="showSetRightDialog(scope.row)"
          >
          分配权限</el-button>
        </template>
      </el-table-column>
      </el-table>
    </el-card>
    <!-- 点击添加角色弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="addRolesDialogVisible"
      @close="addRolesDialogClosed"
      width="50%">
      <el-form :model="addRolesForm"
      :rules="addRolesRules"
      ref="addRolesRef"
      label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
     <!-- 点击编辑角色弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="editRolesDialogVisible"
      @close="editRolesDialogClosed"
      width="50%">
      <el-form :model="editRolesForm"
      :rules="editRolesRules"
      ref="editRolesRef"
      label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input :disabled="true" v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击分配权限按钮弹出框区域 -->
    <el-dialog
      title="分配权限"
      :visible.sync="SetRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
      >
      <el-tree
      :data="rightslist"
      :props="treeProps"
      show-checkbox
      node-key="id"
      default-expand-all
      :default-checked-keys ="defKeys"
      ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightDialogVisible = false">取 消</el-button>
        <el-button type="primary"
        @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 所有角色列表数据
      roleslist: [],
      // 点击添加角色按钮弹出框状态
      addRolesDialogVisible: false,
      // 点击添加角色按钮弹出框状态表单
      addRolesForm: {},
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 0, max: 100, message: '长度在 15 到 100 个字符', trigger: 'blur' }
        ]
      },
      // 编辑角色 弹出框状态
      editRolesDialogVisible: false,
      editRolesForm: {},
      editRolesRules: {
        // roleName: [
        //   { required: true, message: '请输入角色名称', trigger: 'blur' },
        //   { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        // ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 0, max: 100, message: '长度在 15 到 100 个字符', trigger: 'blur' }
        ]
      },
      // 分配权限提示框状态 显示和隐藏
      SetRightDialogVisible: false,
      // 分配权限列表内容
      rightslist: [],
      // 树形嵌套方式/属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值数组
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.roleslist = res.data
      this.$message.success('获取角色列表成功！')
    },
    // 点击关闭，关闭弹出框的内容
    addRolesDialogClosed () {
      this.$refs.addRolesRef.resetFields()
    },
    // 点击添加按钮添加角色
    addRole () {
      this.$refs.addRolesRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('roles', this.addRolesForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败！')
        }
        this.$message.success('添加角色成功！')
        this.addRolesDialogVisible = false
        this.getRolesList()
      })
    },
    // 展示编辑弹框
    async showEditRole (id) {
      // console.log(id)
      this.editRolesDialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色信息失败！')
      }
      this.editRolesForm = res.data
      console.log(this.editRolesForm)
    },
    // 关闭编辑角色弹框
    editRolesDialogClosed () {
      this.$refs.editRolesRef.resetFields()
    },
    // 编辑角色
    editRole () {
      this.$refs.editRolesRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.put('roles/' +
        this.editRolesForm.roleId, {
          roleName: this.editRolesForm.roleName,
          roleDesc: this.editRolesForm.roleDesc
        })
        console.log(res.data)
        if (res.meta.status !== 200) {
          this.$message.error('更新角色信息失败！')
        }
        console.log(res.data)
        // 隐藏编辑角色弹框
        this.editRolesDialogVisible = false
        // 刷新角色数据
        this.getRolesList()
        // 提示编辑成功
        this.$message.success('更新角色信息成功！')
      })
    },
    async removeRoleById (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      this.$message.success('已确认删除！')
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      this.getRolesList()
    },
    // 三级渲染 根据id删除tag
    async removeRightById (role, rightId) {
      // console.log(id)
      // 弹框是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(confirmResult)
      // 如果等于cancel 则提示不删除
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除权限！')
      }
      // 如果confirm字符串则调用后端数据
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      // this.getRolesList()因为会关闭
      role.chilren = res.data
      this.$message.success('已删除权限！')
    },
    // 展示分配权限提示框事件
    async showSetRightDialog (role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取分配权限信息失败！')
      }
      this.rightslist = res.data
      this.$message.success('获取分配权限信息成功！')
      // 递归获取三级节点
      this.getLeafKeys(role, this.defKeys)
      this.SetRightDialogVisible = true
    },
    // 递归函数，存储三级权限id
    // 通过递归的形式，获取角色下所有的三级权限id，并保存到defKeys数组中
    getLeafKeys (node, arr) {
      // 如果当前节点不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed () {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights (id) {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      // console.log(keys)
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功！')
      this.getRolesList()
      this.SetRightDialogVisible = false
    }
  }

}
</script>

<style lang="less" scoped>
.roles{
  .el-tag{
    margin:7px;
  }
  .bdtop{
    border-top: 1px solid #eee;
  }
  .dbbottom{
    border-bottom: 1px solid #eee;
  }
  .vcenter{
    display:flex;
    align-items:center;
  }
}
</style>
